package com.liangzi.service_core.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.liangzi.liangzi_common.result.R;
import com.liangzi.liangzi_common.util.ArgumentEnum;
import com.liangzi.service_core.pojo.entity.VisitUserWeixinOpen;
import com.liangzi.service_core.pojo.vo.UserInfoVO;
import com.liangzi.service_core.pojo.vo.WXPhoneVO;
import com.liangzi.service_core.service.VisitUserService;
import com.liangzi.service_core.service.VisitUserWeixinOpenService;
import com.liangzi.service_core.util.MdzwUtils;
import com.liangzi.service_core.util.WXBizDataCrypt;
import com.liangzi.servicebase.util.RedisUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 小程序用户表 前端控制器
 * </p>
 *
 * @author zhj
 * @since 2021-12-13
 */
@Api(description = "用户接口")
@RestController
@RequestMapping("/web/visitUser")
@Slf4j
public class VisitUserController {

    @Autowired
    public VisitUserWeixinOpenService visitUserWeixinOpenService;
    @Autowired
    public VisitUserService visitUserService;
    @Autowired
    private RedisUtil redisUtil;


    //每次发送code码获取用户openid
    @ApiOperation("login：根据code获取用户微信登录的openid")
    @GetMapping("login/{code}")
    public R login(
            @PathVariable String code,
            UserInfoVO userInfoVO
    ) {
        //拼接url
        StringBuilder url = new StringBuilder("https://api.weixin.qq.com/sns/jscode2session?");
        url.append("appid=");//appid设置
        url.append(ArgumentEnum.APP_ID.getValue());
        url.append("&secret=");//secret设置
        url.append(ArgumentEnum.APP_SECRET.getValue());
        url.append("&js_code=");//code设置
        url.append(code);
        url.append("&grant_type=authorization_code");
        Map<String, Object> map = null;
        String rd_session = "";
        Object userInfo = null;
        try {
            HttpClient client = HttpClientBuilder.create().build();//构建一个Client
            HttpGet get = new HttpGet(url.toString());    //构建一个GET请求
            HttpResponse response = client.execute(get);//提交GET请求
            HttpEntity result = response.getEntity();//拿到返回的HttpResponse的"实体"
            String content = EntityUtils.toString(result);
            System.out.println(content);//打印返回的信息
            JSONObject res = (JSONObject) JSONObject.parse(content);//把信息封装为json
            //把信息封装到map
            map = MdzwUtils.parseJSON2Map(res);
            // 保存到数据库
            log.info(map.toString());
            if (ArgumentEnum.WX_REQUEST_CODE.getValue().equals(map.get("errcode"))) { // 如果map.get("errcode") 等于说明有openid
                return R.error().message("微信请求接口失败");
            }
            String sessionKey = (String) map.get("session_key");
            String openid = (String) map.get("openid");
            log.info("用户的openId -----------------" + openid);
            // 去数据库里，如果有则登录  如果没有则存库
            rd_session = visitUserService.queryOrSaveOpenId(openid, sessionKey, userInfoVO);

            // 去缓存中拿取userId
            String userId = (String) redisUtil.get("session:" + rd_session);
            userInfo = JSON.parse(redisUtil.get(userId).toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "".equals(rd_session) ? R.error().message("session获取失败") : R.ok().data(ArgumentEnum.SESSION_RD_SESSION.getValue(), rd_session).data("userInfo", userInfo).message("session获取成功");
    }

    //
    //@ApiOperation("获取微信绑定手机号")
    //@PostMapping("getUserPhone/{code}")
    //public R getUserPhone(
    //        //@PathVariable("rdSession") String rdSession,
    //       //@RequestBody WXPhoneVO wxPhoneVO
    //        @PathVariable("code") String code
    //) {
    //    // 判断是否登录
    //    //String userId = (String) redisUtil.get("session:" + rdSession);
    //    //if (userId == null) {
    //    //    return R.error().message("请重新登录");
    //    //}
    //    //拼接url
    //    StringBuilder url = new StringBuilder("https://api.weixin.qq.com/sns/jscode2session?");
    //    url.append("appid=");//appid设置
    //    url.append("wx07f9b9d8926ea8b6");
    //    url.append("&secret=");//secret设置
    //    url.append("f846909926c2b943b5652327a099ce89");
    //    url.append("&js_code=");//code设置
    //    url.append(code);
    //    url.append("&grant_type=authorization_code");
    //    Map<String, Object> map = null;
    //    String rd_session = "";
    //    Object userInfo = null;
    //    try {
    //        HttpClient client = HttpClientBuilder.create().build();//构建一个Client
    //        HttpGet get = new HttpGet(url.toString());    //构建一个GET请求
    //        HttpResponse response = client.execute(get);//提交GET请求
    //        HttpEntity result = response.getEntity();//拿到返回的HttpResponse的"实体"
    //        String content = EntityUtils.toString(result);
    //        System.out.println(content);//打印返回的信息
    //        JSONObject res = (JSONObject) JSONObject.parse(content);//把信息封装为json
    //        //把信息封装到map
    //        map = MdzwUtils.parseJSON2Map(res);
    //
    //    } catch (Exception e) {
    //        e.printStackTrace();
    //    }
    //    //System.out.println(map);
    //    String sessionKey = (String) map.get("session_key");
    //    String openid = (String) map.get("openid");
    //    System.err.println(sessionKey + "   " + openid);
    //    return R.ok().data("sessionKey",sessionKey);
    //
    //
    //}







}

